package top.abrsm.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import top.abrsm.entity.StudentEntity;
import top.abrsm.service.IStudentService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class StoreInterceptor implements HandlerInterceptor {

    @Resource
    private IStudentService iStudentService;

    @Override
    public boolean preHandle ( HttpServletRequest request, HttpServletResponse response, Object handler ) throws Exception {
        StudentEntity studentEntity = ( StudentEntity ) request.getSession ().getAttribute ( "studentEntity" );
        if ( studentEntity == null ) {
            request.getRequestDispatcher ( "/toLogin" ).forward ( request, response );
            return false;
        }
        // 当查到登录用户之后再次判断token和数据库中是否一样，如果不一样则说明重复登录了
//        StudentEntity student = iStudentService.getBaseMapper ().selectById ( studentEntity.getId () );
//        if ( ! studentEntity.getToken ().equals ( student.getToken () ) ) {
//            request.getSession ().removeAttribute ( "studentEntity" );
//            // 针对ajax请求做拦截
//            String XRequested = request.getHeader ( "X-Requested-With" );
//            if ( "XMLHttpRequest".equals ( XRequested ) ) {
//                response.setHeader ( "Content-type", "text/html;charset=utf-8" );
//                response.getWriter ().write ( "isAjax" );
//                response.getWriter ().flush ();
//                response.getWriter ().close ();
//            } else {
//                request.getRequestDispatcher ( "/toLogin" ).forward ( request, response );
//            }
//            return false;
//        }
        return true;
    }

    @Override
    public void postHandle ( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView ) throws Exception {

    }

    @Override
    public void afterCompletion ( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex ) throws Exception {

    }
}
